package com.yohann.algorithm;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * <p>
 * 哈夫曼树演示
 * </p>
 *
 * @author Yohann
 * @since 2021/1/6 20:12
 */
public class HuffmanTreeDemo {
    public static void main(String[] args) {
        int[] arr = new int[]{13, 7, 8, 3, 29, 6, 1};
        Node node = generateHuffmanTree(arr);
        node.preOrder();
    }

    //构建哈夫曼树
    public static Node generateHuffmanTree(int[] arr) {
        List<Node> nodes = new ArrayList<>();
        for (int value : arr) {
            nodes.add(new Node(value));
        }

        //从小到大排序
        while (nodes.size() > 1) {
            Collections.sort(nodes);

            Node left = nodes.get(0);
            Node right = nodes.get(1);
            Node parent = new Node(left.value + right.value);
            parent.left = left;
            parent.right = right;

            nodes.remove(left);
            nodes.remove(right);
            nodes.add(parent);
        }

        return nodes.get(0);
    }
}

/**
 * 节点
 */
class Node implements Comparable<Node> {
    int value;
    Node left;
    Node right;

    public Node(int value) {
        this.value = value;
    }

    @Override
    public String toString() {
        return "Node{" +
                "value=" + value +
                '}';
    }

    @Override
    public int compareTo(Node o) {
        return this.value - o.value;
    }

    public void preOrder() {
        preOrder(this);
    }

    private void preOrder(Node node) {
        System.out.println(node);

        if (node.left != null) {
            preOrder(node.left);
        }

        if (node.right != null) {
            preOrder(node.right);
        }
    }
}